package com.kob.backend.service.impl.user.account;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kob.backend.mapper.UserMapper;
import com.kob.backend.pojo.user;
import com.kob.backend.service.user.account.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public Map<String, String> register(String username, String password,String email,String phone,String address) {
        Map<String, String> map = new HashMap<>();
        if (username == null) {
            map.put("error_message", "用户名不能为空");
            return map;
        }
        if (email== null) {
            map.put("error_message", "邮箱不能为空");
            return map;
        }
        if (phone== null) {
            map.put("error_message", "电话号码不能为空");
            return map;
        }
        if (address== null) {
            map.put("error_message", "地址不能为空");
            return map;
        }
        if (password == null) {
            map.put("error_message", "密码不能为空");
            return map;
        }

        username = username.trim();//删掉用户名首尾的空格，制表符等
        if (username.length() == 0) {
            map.put("error_message", "用户名不能为空");
            return map;
        }
        if(password.length()==0)
        {
            map.put("error_message","密码不能为空");
            return map;
        }
        if(email.length()==0)
        {
            map.put("error_message","邮箱不能为空");
            return map;
        }
        if(phone.length()==0)
        {
            map.put("error_message","手机号不能为空");
            return map;
        }
        if(address.length()==0)
        {
            map.put("error_message","地址不能为空");
            return map;
        }
        if (username.length() > 20) {
            map.put("error_message", "用户名过长,不能大于20");
            return map;
        }

        if (password.length() > 400) {
            map.put("error_message", "密码过长,不能大于400");
            return map;
        }

        QueryWrapper<user> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        List<user> users = userMapper.selectList(queryWrapper);
        if (!users.isEmpty()) {
            map.put("error_message", "用户已存在");
            return map;
        }
        String encodePassword=passwordEncoder.encode(password);
        user this_user=new user(null,username,encodePassword,email,phone,address);//id自增
        userMapper.insert(this_user);
        map.put("error_message","success");
        return map;
    }
}
